//
//  GuideViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/18.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "GuideViewController.h"
#import "SDCycleScrollView.h"
#import "AppDelegate.h"
#import "QuickScanViewController.h"
#import "OSSHelper.h"

@interface GuideViewController ()
{
    NSTimer *timer;//定时器
    int count;//记录时间
}
@property (weak, nonatomic) IBOutlet UIButton *skipButton;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property(nonatomic,strong)SDCycleScrollView *cycleView;
@property(nonatomic,strong)NSMutableArray *pathArr;
@end
//20170610134035445679
@implementation GuideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //本地路径。创建文件夹
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Guide"];
    BOOL is= [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
    if(is){
        DLog(@"目录创建成功 ");
    }else{
        DLog(@"目录已存在 ");
    }
    self.pathArr = [NSMutableArray array];

    //轮播图
    [self cyleVIew];
    //2.1 引导页接口
    [self loadData];
    //计时器，6秒时切换控制器
    count=10;
    self.timeLabel.text = @"跳过10S";
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    [self.view bringSubviewToFront:self.timeLabel];
    [self.view bringSubviewToFront:self.skipButton];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.cycleView removeFromSuperview];
    
}

-(void)loadData{
    self.imageUrlArray = [NSMutableArray array];
    NSDictionary *paraDic = @{
                              @"gpid":@"2",
                              @"gptype":@"0"
                              };
    
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GUIDEPIC paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"引导页--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *list = resultDic[@"data"];
            if([list isKindOfClass:[NSNull class]]) return ;
            for(NSDictionary *dic in list){
                [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:dic[@"url"]  downLoadBlock:^(NSData *data) {
                    //保存到本地
                    [weakSelf saveTolocal:data count:list.count];
                }];
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)saveTolocal:(NSData*)imageData count:(NSInteger)zcount{
    NSString *imageName ;
    UIImage *image= [UIImage imageWithData:imageData];
    if(UIImagePNGRepresentation(image)){//返回为png图像
        imageName = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    }else{ //返回为JPEG图像
        imageName = [NSString stringWithFormat:@"%@.jpeg",[self getTimeNow]];
    }
    //本地路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Guide"];
    //创建文件
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
    BOOL isSuccess= [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:nil];
    if(!isSuccess){
        NSLog(@"失败");
    }
    DLog(@"path---%@",path);
    if(isSuccess){
        //回到主线城刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.pathArr addObject:path];
            if(self.pathArr.count==zcount){
                self.cycleView.localizationImageNamesGroup = self.pathArr;
           
            }
        });
    }
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}


//跳过
- (IBAction)skipAction:(UIButton *)sender {
    [timer invalidate];
    timer = nil;
//    QuickScanViewController *quick = [[QuickScanViewController alloc]init];
//    quick.count =  1;
    SelecedViewController *quick = [[SelecedViewController alloc]init];
    [UIApplication sharedApplication].keyWindow.rootViewController = quick;
    [[AppDelegate appDealegate].window setRootViewController: quick];
}

- (void)changeTime{
    count--;
    if(count==0){
        [timer invalidate];
        timer = nil;
//        QuickScanViewController *quick = [[QuickScanViewController alloc]init];
//        quick.count =  1;
//        [self presentViewController:quick animated:YES completion:nil];
        SelecedViewController *quick = [[SelecedViewController alloc]init];
        [UIApplication sharedApplication].keyWindow.rootViewController = quick;
        [[AppDelegate appDealegate].window setRootViewController: quick];
    }else{
    NSString *title = [NSString stringWithFormat:@"跳过%dS",count];
    self.timeLabel.text = title;
    }
}

- (void)cyleVIew{
    //轮播图
    self.cycleView =[ SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height) shouldInfiniteLoop:NO imageNamesGroup:nil];
    self.cycleView.currentPageDotImage = [UIImage imageNamed:@"lunbodian_nor"];
    self.cycleView.pageDotImage = [UIImage imageNamed:@"lunbodian_sel"];
    self.cycleView.autoScrollTimeInterval = 5.0;
    [self.view addSubview:self.cycleView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
